package com.rz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.admin.entity.Res;
import com.rz.admin.entity.RoleResource;
import com.rz.admin.mapper.RoleResourceMapper;
import com.rz.admin.service.IAdminRoleService;
import com.rz.admin.service.IResService;
import com.rz.admin.service.IRoleResService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RoleResService extends ServiceImpl<RoleResourceMapper, RoleResource> implements IRoleResService {

    @Resource
    private IAdminRoleService adminRoleService;
    @Resource
    private IResService resService;
    @Resource
    private RoleResourceMapper roleResourceMapper;

    @Override
    public List<RoleResource> getByRoleId(List<Integer> roleIds) {
        QueryWrapper<RoleResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id",roleIds);
        return list(queryWrapper);
    }

    @Override
    public List<Integer> getResIdByRoleId(List<Integer> roleIds) {
        Set<Integer> resIds = new HashSet<>();
        List<RoleResource> roleResources = getByRoleId(roleIds);
        if(roleResources!=null && roleResources.size()>0){
            roleResources.forEach(roleResource -> resIds.add(roleResource.getResId()));
        }
        return new ArrayList<>(resIds);
    }

    @Override
    public List<Res> getResByAdminId(Integer adminId,boolean showBtn) {
        List<Integer> roleIds = adminRoleService.getRoleIdsByAdminId(adminId);
        List<Integer> resIds = getResIdByRoleId(roleIds);
        List<Res> resList = new ArrayList<>(resService.listIdsWarpper(resIds,showBtn));
        List<Res> newResList = new ArrayList<>();
        List<Res> parentList = resList.stream().filter(item->item.getParentId().equals(0)).collect(Collectors.toList());
        buildSortedRes(parentList,resList,newResList);
        return newResList;
    }

    private void buildSortedRes(List<Res> parentList,List<Res> list,List<Res> newResList){
        parentList.forEach(item->{
            newResList.add(item);
            List<Res> children = list.stream()
                    .filter(child->child.getParentId().equals(item.getId()))
                    .sorted(Comparator.comparingInt(Res::getSortBy))
                    .collect(Collectors.toList());
            buildSortedRes(children,list,newResList);
        });
    }

    @Override
    public int deleteByRoleId(Integer roleId) {
        return roleResourceMapper.deleteByRoleId(roleId);
    }

    @Override
    public List<Res> getResTreeByAdminId(Integer adminId,boolean showBtn) {
        return resService.buildResTree(new ArrayList<>(getResByAdminId(adminId,showBtn)));
    }
}
